import { getToken, setToken, removeToken } from '_utils/auth'
import { login, getInfo, logout } from '_api'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avator: '',
    roles: [] // 角色权限
  }
}

const state = getDefaultState()
console.log(state.token)
const mutations = {
  REST_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  // 设置token
  SET_TOKEN: (state, token) => {
    state.token = token
  },

  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATOR: (state, avator) => {
    state.avator = avator
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // 登录
  login ({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      login({ userName: username, password: password }).then(res => {
        const { data } = res
        console.log(data)
        commit('SET_TOKEN', data.token) // 存token
        setToken(data.token)
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 获取角色
  getInfo ({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo({ token: state.token }).then(response => {
        const { data } = response
        console.log(data)
        if (!data) {
          alert('获取权限失败 请重新登录')
        }
        // 角色具体信息
        const { roles, name, avator } = data
        if (!roles || roles.length <= 0) {
          alert('请用用户加权限')
        }
        // 权限
        commit('SET_ROLES', roles)
        // 姓名
        commit('SET_NAME', name)
        // 头像
        commit('SET_AVATOR', avator)
        resolve(data)
      }).catch(error => {
        reject(error)
      })
    }
    )
  },

  // 退出登录
  logout ({ commit, state }) {
    console.log(1515)
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  // resetToken ({ commit }) {
  //   return new Promise(resolve => {
  //     commit('SET_TOKEN', '')
  //     commit('SET_ROLES', [])
  //     removeToken()
  //     resolve()
  //   })
  // }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
